import api from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {
  // filterMenuRoutes,
  handlerRedirect,
  handlerMenuRoutes
} from '@/utils/router-filter'
import { Message } from 'element-ui'
import { deepClone } from '@/utils'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    roleName: '',
    roleId: '',
    avatar: '',
    isAddRoutes: false,
    allRoutes: [],
    menuRoutes: [],
    authList: [],
    roleList: [],
    userName: '',
    deptId: '',
    userId: '',
    avatarUrl: ''
  }
}

const state = getDefaultState()

const mutations = {
  // 动态添加菜单路由
  SET_MENUROUTES(state, menuRoutes) {
    state.menuRoutes = menuRoutes

    router.options.routes = router.options.routes.map((e) => {
      if (e.path === '/' && e.children) {
        const menuList = [
          ...state.menuRoutes,
          {
            path: '/home',
            name: 'Home',
            hidden: true,
            component: () => import('@/views/home/index'),
            meta: {
              title: '首页',
              breadcrumb: false,
              isHiddenSlider: true
            }
          }
        ]
        e.children = Array.from(new Set(menuList.map((item) => item.name))).map(
          (name) => {
            return menuList.find((item) => item.name === name)
          }
        )
      }
      return e
    })
    const routes = router.options.routes
    // 重定向404路由，必须放在最后添加，防止登录或刷新显示404
    state.allRoutes = routes.concat([
      { path: '*', redirect: '/404', hidden: true }
    ])
    resetRouter()
    router.addRoutes(state.allRoutes)
    state.isAddRoutes = true
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  UPDATE_INFO: (state, name) => {
    const { fullName, avatarUrl } = name
    state.name = fullName
    state.avatarUrl = avatarUrl
  },
  SET_NAME: (state, name) => {
    const { fullName, userName, roleName, roleId, avatarUrl, deptId, userId } =
      name
    state.name = fullName
    state.userName = userName
    state.roleName = roleName
    state.roleId = roleId
    state.avatarUrl = avatarUrl
    state.deptId = deptId
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENU_LIST: (state, list) => {
    state.menuList = list
  },
  SET_AUTH_LIST: (state, list) => {
    state.authList = list
  },
  SET_ROLE_LIST: (state, list) => {
    state.roleList = list
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { userName, password, mainUserName } = userInfo
    return new Promise((resolve, reject) => {
      api
        .login({ userName: userName.trim(), password, mainUserName })
        .then((response) => {
          const { data } = response
          if (response.code === '1000') {
            Message.success({
              message: '登录成功',
              type: 'success',
              duration: 1500
            })
          }
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      api
        .getInfo(state.token)
        .then((response) => {
          const { data } = response
          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          const {
            fullName,
            avatar,
            menuList = [],
            userName,
            roleName,
            roleList = [],
            roleId,
            userId,
            avatarUrl,
            deptId
          } = data
          const filetrMenuList = JSON.parse(
            JSON.stringify(
              menuList.filter((e) => e.type === 1 || e.type === 3) || []
            )
          )
          // 0:目录,1:菜单,2:按钮,9:埋点
          // TO1 系统配置菜单
          const asyncMenu = handlerMenuRoutes(deepClone(filetrMenuList))

          const newRoutes = handlerRedirect(asyncMenu)
          commit('SET_MENUROUTES', newRoutes)
          commit('SET_NAME', {
            fullName,
            userName,
            roleName,
            roleId,
            avatarUrl,
            userId,
            deptId
          })
          commit('SET_AVATAR', avatar)
          commit('SET_AUTH_LIST', menuList)
          commit('SET_ROLE_LIST', roleList)
          commit('tabs/SET_TABS', [], { root: true })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  updateInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      api
        .getUserCenterInfo()
        .then((response) => {
          const { data } = response
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { fullName, avatarUrl } = data
          commit('UPDATE_INFO', { fullName, avatarUrl })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      api
        .logout(state.token)
        .then(() => {
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },
  saveMenuList({ commit, state }) {
    commit('SET_MENU_LIST', state)
  },
  saveAuthList({ commit, state }) {
    commit('SET_AUTH_LIST', state)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
